package com.exam.controller.subject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.exam.common.vo.ExamStuVO;
import com.exam.common.vo.ExamSubjectVO;
import com.exam.common.vo.ExamTeacherVO;
import com.exam.common.vo.MenuVO;
import com.exam.common.vo.UserVO;
import com.exam.common.vo.page.PageModel;
import com.exam.entity.ExamSubject;
import com.exam.service.role.RoleService;
import com.exam.service.subject.SubjectService;

@Controller
@RequestMapping("/subject")
public class SubjectController {

	@Autowired
	RoleService roleService;
	
	@Autowired
	SubjectService subService;
	
	@RequestMapping(value="/subjectList")
	public String subjectList(Model model,HttpSession session){
		List<MenuVO> mnList = new ArrayList<MenuVO>();
		ExamStuVO sVO = (ExamStuVO) session.getAttribute("stuVO");
		if(sVO!=null){
		UserVO userVO = new UserVO();
		userVO.setUserName(sVO.getExamStuNumber());
		userVO.setUserPwd(sVO.getExamStuPassword());
		
		mnList = roleService.getMenuVO(userVO);
		session.setAttribute("mnList",mnList);
		}
		
		PageModel<ExamSubjectVO> page = subService.findByPage();
		model.addAttribute("page",page);
		ExamTeacherVO teacherVO = (ExamTeacherVO) session.getAttribute("teacher");
		ExamStuVO stuVO = (ExamStuVO) session.getAttribute("stuVO");
		if(teacherVO != null){
			model.addAttribute("readonly","");
		}else if(stuVO != null){
			model.addAttribute("readonly","readonly");
		}
		
		return "/subject/subList";
	}
	
	@RequestMapping(value="/state",method=RequestMethod.POST)
	public void updateState( HttpServletRequest request,HttpServletResponse response) throws IOException{
		String state = request.getParameter("subState").trim();
		String subId = request.getParameter("subId").trim();
		
		if(state == "1"||state.equals("1"))
			response.getWriter().write("1");
		else{
			response.getWriter().write("0");
		}
		
		ExamSubject sub = new ExamSubject();
		
		ExamSubjectVO subVO =  subService.findById(Integer.parseInt(subId));
		subVO.setExamSubjectFlag(Integer.parseInt(state));
		if(subVO != null){
			BeanUtils.copyProperties(subVO, sub);
		}
		subService.update(sub);
	}
}
